package com.l.im.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.l.im.common.auth.JwtSecret;
import com.l.im.common.cache.RedisService;
import com.l.im.strategy.RouteStrategy;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

/**
 * @program: LIM
 * @description: http处理逻辑类
 * @author: Alex Wu
 * @createDate: 2025-04-14 17:59
 **/
@Slf4j
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final RouteStrategy routeStrategy;
    private List<String> servers;

    public HttpRequestHandler(RouteStrategy routeStrategy,List<String> servers) {
        this.routeStrategy = routeStrategy;
        this.servers = servers;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        String uri = msg.uri();

        if ("/lim/auth/token".equals(uri)) {
            handleAuthRequest(ctx, msg);
        } else {
            // 如果不是 /getNode 请求，继续路由到其他服务器
            handleRequest(ctx, msg);
        }
    }

    private void handleAuthRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
        try {
            String json = request.content().toString(StandardCharsets.UTF_8);
            JSONObject body = JSON.parseObject(json);
            String appId = body.getString("appId");
            String appSecret = body.getString("appSecret");
            log.info("appId: {}, appSecret: {}", appId, appSecret);
            log.info("servers:", this.servers);

            // 校验 appId 和 appSecret（你可以替换为从数据库或者配置文件中校验）
           /* if (!JwtUtil.isValidAppIdAndSecret(appId, appSecret)) {
                sendJson(ctx, "{\"code\":401, \"msg\":\"Invalid appId or appSecret\"}", HttpResponseStatus.UNAUTHORIZED);
                return;
            }*/

            // 生成 JWT
            String jti = UUID.randomUUID().toString();
            Instant now = Instant.now();
            Instant exp = now.plusSeconds(300); // 5分钟有效期

            String jwt = JwtSecret.generateToken(appId, jti, now, exp);

            RedisService redisService = new RedisService();

            redisService.set("jwt:active:" + appId, jti, 300);


            JSONObject result = new JSONObject();
            result.put("code", 200);
            result.put("token", jwt);
            result.put("expiresIn", 300);
            result.put("node", routeStrategy.getServer(servers));  // 返回节点信息

            sendJson(ctx, result.toJSONString(), HttpResponseStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            sendJson(ctx, "{\"code\":500, \"msg\":\"Internal Server Error\"}", HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private void sendJson(ChannelHandlerContext ctx, String json, HttpResponseStatus status) {
        ByteBuf content = Unpooled.copiedBuffer(json, StandardCharsets.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }




    // 处理 GET /getNode 请求，返回当前的可用服务器列表
    private void handleGetNodeRequest(ChannelHandlerContext ctx) {
        String serverList = String.join(", ", servers);
        String responseMessage = "Available servers: " + serverList;

        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(responseMessage.getBytes())
        );

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

        // 返回服务器列表
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    // 路由请求到可用的服务器
    private void handleRequest(ChannelHandlerContext ctx, FullHttpRequest msg) {
        // 使用路由策略来选择服务器
        String selectedServer = routeStrategy.getServer(servers);

        if (selectedServer != null) {
            String responseMessage = "Redirecting to server: " + selectedServer;

            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(responseMessage.getBytes())
            );

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

            // 将响应发送回客户端
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE,
                    Unpooled.wrappedBuffer("No available servers".getBytes())
            );

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

            // 将响应发送回客户端
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

